package net.martinimix.edesk.search;

import com.bluemartini.dna.BMException;
import com.endeca.navigation.ENEConnection;
import com.endeca.navigation.ENEQuery;
import com.endeca.navigation.ENEQueryException;
import com.endeca.navigation.ENEQueryResults;
import com.endeca.navigation.ERecList;
import com.endeca.navigation.HttpENEConnection;
import com.endeca.navigation.UrlENEQuery;

public class EndecaRecordSearch {

	protected final String endecaHost;
	protected final int endecaPort;
	

	public EndecaRecordSearch(String endecaHost, int endecaPort) {
		this.endecaHost = endecaHost;
		this.endecaPort = endecaPort;
	}

	public ERecList findRecords(String searchTerms) throws BMException {
		
		final UrlENEQuery query;
		
		ERecList endecaRecordList;
		
		try {
			query = new UrlENEQuery("", "UTF-8");
			query.setN("0");
			query.setNtt(searchTerms);
			query.setNtk("Entire Site");
			query.setNtx("mode matchall");
			
			query.setNavNumERecs(Integer.MAX_VALUE);
			endecaRecordList = search(query);
		} catch (ENEQueryException e) {
			throw new BMException("Search failed: " + e.getMessage(), e, null);
		}
		
		return endecaRecordList;
	}
	
	/**
	 * Returns a list of products matching the given Endeca query.
	 * 
	 * @param query the <code>ENEQuery</code> used to find matching records
	 * 
	 * @return an <code>ERecList</code> containing the records matching the
	 * given <code>query</code>
	 * 
	 * @throws ENEQueryException if an error occurs while querying the navigation
	 * engine or the given <code>query</code> is invalid
	 */
	protected ERecList search(ENEQuery query) throws ENEQueryException {
		
		ENEConnection conn = new HttpENEConnection(endecaHost, endecaPort);
		ENEQueryResults results = conn.query(query);
		
		return results.getNavigation().getERecs();
	}

}